package cn.edu.sasu.common.interceptor;
 
import cn.edu.sasu.common.annotation.RoleNum;
import cn.edu.sasu.common.util.CookieUtil;
import cn.edu.sasu.common.util.SessionUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class SecurityInterceptor implements HandlerInterceptor {
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //先查看服务器端是否存在cookie对应的session
        String cookie = CookieUtil.getCookieValueFromRequest(request);
        response.setCharacterEncoding("UTF-8");
        if (!SessionUtil.containsValue(cookie)) {
            response.getWriter().write("{\"code\":-1,\"msg\":\"请先登录\",\"data\":null}");
            return false;
        } else {
            //查看该cookie对应的user_id是否拥有访问该路径的权限
            Integer type = Integer.parseInt(cookie.substring(cookie.length() - 1));
            if (hasPermission(handler, type)) {
                return true;
            } else {
                response.getWriter().write("{\"code\":-1,\"msg\":\"权限不够\",\"data\":null}");
                return false;
            }
        }
    }
 
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
 
    }
 
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
 
    }
 
    private boolean hasPermission(Object handler, Integer type) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 获取方法上的注解
            RoleNum roleNum = handlerMethod.getMethod().getAnnotation(RoleNum.class);
            // 如果方法上的注解为空 则获取类的注解
            if (roleNum == null) {
                roleNum = handlerMethod.getMethod().getDeclaringClass().getAnnotation(RoleNum.class);
            }
            // 如果标记了注解，则判断权限
            if (roleNum != null) {
                if (roleNum.value() == 2) {
                    return true;
                }
                if (roleNum.value() == type) {
                    return true;
                }
                return false;
            }
        }
        return false;
    }
}
 